<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="css/layui.css" rel="stylesheet">
    <script src="js/jquery-1.12.4.min.js"></script>
</head>
<body>
<div id="container" style="margin: 20px">
    <h2>动态</h2>
</div>
<script>
    $(function(){
        $.ajax({
            url: 'post/list?pageNum=1&pageSize=10',
            type: 'get',
            success: function(result) {
                $.each(result.data, function(index, obj) {
                    let likeIcon = obj.like ?
                        '<i class="layui-icon layui-icon-heart-fill" style="font-size: 30px; color: #ff401e;"></i><label>'+obj.post.likeCount+'</label><br>' :
                        '<i class="layui-icon layui-icon-heart-fill" style="font-size: 30px; color: #d4d4d4;"></i><label>'+obj.post.likeCount+'</label><br>'
                    $('#container').append(
                        '<h3>'+obj.post.user.userName+'</h3>' +
                        '<div>'+obj.post.content+'</div>' +
                        `<input type="hidden" value="${obj.post.postId}"/>`+
                        likeIcon + '<br>'
                    );
                });

                //防抖延迟器
                let timer;
                $('.layui-icon').on('click', function() {
                    //取消延迟器
                    clearTimeout(timer);
                    //延迟发起请求
                    timer = setTimeout(()=>{
                        let that = $(this);
                        //点赞或取消点赞操作
                        let postId = that.prev().val();
                        $.ajax({
                            url: 'like',
                            type: 'post',
                            data: {'postId' : postId},
                            success: function(result) {
                                if(result.code === 401) {
                                    location.href = 'login.html';
                                }else if(result.code === 200) {
                                    if(result.data.likeStatus) {
                                        that.css('color', '#ff401e');
                                    }else{
                                        that.css('color', '#d4d4d4');
                                    }
                                    that.next().text(result.data.likeCount);
                                }
                            }
                        });
                    }, 300);
                });
            }
        });
    });
</script>
</body>
</html>